using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Infrastructure.Persistence;
using UwinEducation.Shared.Models;

namespace UwinEducation.Infrastructure.Repositories
{
    /// <summary>
    /// 订单折扣仓储实现
    /// </summary>
    public class OrderDiscountRepository : Repository<OrderDiscount, Guid>, IOrderDiscountRepository
    {
        private readonly ApplicationDbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public OrderDiscountRepository(ApplicationDbContext context) : base(context)
        {
            _context = context;
        }

        /// <summary>
        /// 根据订单ID获取折扣列表
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <returns>订单折扣列表</returns>
        public async Task<List<OrderDiscount>> GetByOrderIdAsync(Guid orderId)
        {
            return await _context.OrderDiscounts
                .Where(d => d.OrderId == orderId)
                .Include(d => d.Order)
                .ToListAsync();
        }

        /// <summary>
        /// 根据多个订单ID获取折扣列表
        /// </summary>
        /// <param name="orderIds">订单ID列表</param>
        /// <returns>订单折扣列表</returns>
        public async Task<List<OrderDiscount>> GetByOrderIdsAsync(List<Guid> orderIds)
        {
            return await _context.OrderDiscounts
                .Where(d => orderIds.Contains(d.OrderId))
                .Include(d => d.Order)
                .ToListAsync();
        }

        /// <summary>
        /// 分页获取订单折扣
        /// </summary>
        /// <param name="request">分页请求参数</param>
        /// <returns>分页结果</returns>
        public async Task<PagedResult<OrderDiscount>> GetPagedAsync(OrderDiscountPageRequest request)
        {
            var query = _context.OrderDiscounts.Include(d => d.Order).AsQueryable();

            // 按条件筛选
            if (request.OrderId.HasValue)
            {
                query = query.Where(d => d.OrderId == request.OrderId.Value);
            }

            // 计算总数
            var total = await query.CountAsync();

            // 分页并排序
            var items = await query
                .OrderByDescending(d => d.CreatedAt)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize)
                .ToListAsync();

            return new PagedResult<OrderDiscount>
            {
                Items = items,
                Total = total
            };
        }

        /// <summary>
        /// 批量添加订单折扣
        /// </summary>
        /// <param name="discounts">订单折扣列表</param>
        /// <returns>操作结果</returns>
        public async Task AddRangeAsync(List<OrderDiscount> discounts)
        {
            await _context.OrderDiscounts.AddRangeAsync(discounts);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 批量更新订单折扣
        /// </summary>
        /// <param name="discounts">订单折扣列表</param>
        /// <returns>操作结果</returns>
        public async Task UpdateRangeAsync(List<OrderDiscount> discounts)
        {
            _context.OrderDiscounts.UpdateRange(discounts);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 批量删除订单折扣
        /// </summary>
        /// <param name="discounts">订单折扣列表</param>
        /// <returns>操作结果</returns>
        public async Task DeleteRangeAsync(List<OrderDiscount> discounts)
        {
            _context.OrderDiscounts.RemoveRange(discounts);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 计算订单的总折扣金额
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <returns>总折扣金额</returns>
        public async Task<decimal> GetTotalDiscountAmountAsync(Guid orderId)
        {
            return await _context.OrderDiscounts
                .Where(d => d.OrderId == orderId)
                .SumAsync(d => d.DiscountAmount);
        }

        /// <summary>
        /// 计算多个订单的总折扣金额
        /// </summary>
        /// <param name="orderIds">订单ID列表</param>
        /// <returns>每个订单ID对应的总折扣金额字典</returns>
        public async Task<Dictionary<Guid, decimal>> GetTotalDiscountAmountByOrderIdsAsync(List<Guid> orderIds)
        {
            var discounts = await _context.OrderDiscounts
                .Where(d => orderIds.Contains(d.OrderId))
                .ToListAsync();

            return discounts
                .GroupBy(d => d.OrderId)
                .ToDictionary(
                    g => g.Key,
                    g => g.Sum(d => d.DiscountAmount)
                );
        }

        /// <summary>
        /// 根据ID获取订单折扣
        /// </summary>
        /// <param name="id">订单折扣ID</param>
        /// <returns>订单折扣实体</returns>
        public override async Task<OrderDiscount> GetByIdAsync(Guid id)
        {
            return await _context.OrderDiscounts
                .Include(d => d.Order)
                .FirstOrDefaultAsync(d => d.Id == id);
        }
    }
}
